<template>
  <div class="basic-config">
    <!-- :wrapper-col="{ span: 10 }" -->
    <!-- {{ formData.bind }} -->
    <!-- {{ siteClassificationTableData }} -->
    <a-form-item label="资源名称" name="name">
      <a-input
        v-model:value.trim="formData.name"
        placeholder="请输入资源名称"
        :maxlength="30"
        class="w-[440px]"
        :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
      >
      </a-input>
    </a-form-item>

    <a-form-item label="资源类型" name="resource_type">
      <div class="resource-type">
        <a-select
          v-model:value="formData.resource_type"
          :options="NEW_RESOURCE_TYPE"
          placeholder="请选择资源类型"
          class="w-[440px]"
          :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
          @select="selectResetValueHandle"
        >
        </a-select>
        <div class="describe mt-[8px]">
          1、种源资源，采集种源系统资源；2、外部资源，采集第三方外部资源，地址包含域名；
        </div>
      </div>
    </a-form-item>

    <a-form-item label="内容类型" name="content_type">
      <a-select
        v-model:value="formData.content_type"
        :options="NEW_CONTENT_TYPE"
        placeholder="请选择内容类型"
        class="w-[440px]"
        :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
        @dropdownVisibleChange="dropdownVisibleChangeHandle"
      >
      </a-select>
    </a-form-item>

    <div v-if="collectTypeVisible">
      <a-form-item label="文件类型" name="video_resource_type" v-if="seedSourceApiVisible">
        <a-checkbox-group v-model:value="formData.video_resource_type">
          <a-checkbox :value="item.value" v-for="item in LINK_TYPE" :key="item.value" class="mr-[37px]">{{
            item.label
          }}</a-checkbox>
        </a-checkbox-group>
      </a-form-item>

      <a-form-item
        label="接口地址"
        name="collect_addr"
        class="collect-type"
        v-if="seedSourceApiVisible || externalApiVisible"
      >
        <div class="input-content">
          <a-input v-model:value="formData.collect_addr" placeholder="请输入接口地址" class="w-[440px]"> </a-input>
          <a-button
            type="primary"
            :disabled="!formData.collect_addr"
            :loading="resourceClassifyBtnLoading"
            @click="setSourceClassificationHandle"
            >获取资源分类</a-button
          >
        </div>
        <a-form-item-rest v-if="formData.resource_type === 2">
          <span class="describe">与外部资源系统对接好的采集接口地址</span>
        </a-form-item-rest>
      </a-form-item>

      <a-form-item label="种源密钥" name="seed_key" v-if="seedSourceApiVisible">
        <div class="resource-type">
          <a-input v-model:value="formData.seed_key" placeholder="请输入种源密钥" class="w-[440px]"> </a-input>
          <div class="describe">种源系统开启密钥采集时，需填写密钥才能采集</div>
        </div>
      </a-form-item>

      <a-form-item label="其他参数" name="other_param" v-if="seedSourceApiVisible || externalApiVisible">
        <a-input
          v-model:value="formData.other_param"
          placeholder=" 一般使用&开头，例如只获取某个线路 &play=iqiyi，多个参数使用&拼接"
          class="w-[480px]"
        >
        </a-input>
      </a-form-item>

      <a-form-item label="接口类型" name="interface_type" v-if="externalApiVisible">
        <a-radio-group v-model:value="formData.interface_type">
          <a-radio :value="item.value" v-for="item in API_TYPE" :key="item.value">{{ item.label }}</a-radio>
        </a-radio-group>
      </a-form-item>
    </div>

    <a-form-item label="数据处理" name="data_handing">
      <a-radio-group v-model:value="formData.data_handing">
        <a-radio :value="item.value" v-for="item in DATA_PROCESSING" :key="item.value" class="mr-[82px]">{{
          item.label
        }}</a-radio>
      </a-radio-group>
    </a-form-item>

    <a-divider />

    <MessageTitle mainText="绑定分类" lessText="说明：未绑定的分类将不会被采集" class="mt-[8px]" />

    <a-form-item label="采集到站点" name="site_id">
      {{ formData.site_id }}
      <a-select
        v-model:value="formData.site_id"
        :options="NEW_STATION"
        placeholder="请选择站点"
        class="w-[440px]"
        :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
        @change="siteSelectChange"
      />
    </a-form-item>

    <a-form-item label="" name="contentQuantity" class="ml-[104px]">
      <a-form-item-rest>
        <SiteClassificationTable :data="siteClassificationTableData" :isSelect="SiteClassificationSelectVisible" />
      </a-form-item-rest>
    </a-form-item>

    <a-form-item label="状态" name="status">
      <a-radio-group v-model:value="formData.status">
        <a-radio :value="item.value" v-for="item in COLLECT_START_STATE_2" :key="item.value" class="mr-[82px]">{{
          item.label
        }}</a-radio>
      </a-radio-group>
    </a-form-item>
  </div>
</template>

<script lang="ts" setup name="BasicConfig">
import SiteClassificationTable from '../../components/site-classification-table/index.vue'
import MessageTitle from '../../components/MessageTitle.vue'
import { ref, computed, watch, toRefs } from 'vue'
import type { FilterValuesType } from '@/stores/modules/collect-manage/select-data-source'
import {
  COLLECT_START_STATE_2,
  LINK_TYPE,
  API_TYPE,
  DATA_PROCESSING,
  RESOURCE_TYPE,
  STATION,
  CONTENT_TYPE,
  SITE_CLASSIFICATION,
  getStation,
  getSiteClassification,
  filterSelectSource
} from '@/stores/modules/collect-manage/select-data-source'
import { Modal, message } from 'ant-design-vue'
import type { CollectFormBindType, CollectFormType } from '../../public-type'
import type {
  SourceClassificationDataItemType,
  SourceClassificationDataType
} from '../../components/site-classification-table/type'
import mitt from '@/utils/mitt'
import apis from '@/apis'
// props
type Props = { formData: CollectFormType; formRef: any }
const props = defineProps<Props>()
const { formData, formRef } = toRefs(props)

// 获取站点分类
getStation({
  site_id: undefined,
  site_keyword: undefined,
  site_type: formData.value.resource_type,
  site_status: 1
})

// 采集到站点
const NEW_STATION = computed(() => {
  let filterValues: FilterValuesType = [0]
  return filterSelectSource(STATION.value, filterValues)
})

// 站点绑定 select 是否显示
const SiteClassificationSelectVisible = computed(() => formData.value.site_id !== undefined)

// 资源类型字典
const NEW_RESOURCE_TYPE = computed(() => {
  let filterValues: FilterValuesType = [0]
  return filterSelectSource(RESOURCE_TYPE, filterValues)
})

// 内容类型字典
const NEW_CONTENT_TYPE = computed(() => {
  if (!formData.value.resource_type) return []

  let filterValues: FilterValuesType = []

  if (formData.value.resource_type === 1) {
    filterValues = [0, 2, 3, 4]
  } else if (formData.value.resource_type === 2) {
    filterValues = [0, 4]
  }

  return filterSelectSource(CONTENT_TYPE, filterValues)
})

// 根据资源种类显示隐藏对应字段
const collectTypeVisible = computed(() => formData.value.resource_type)

// 种源接口采集
const seedSourceApiVisible = computed(() => getNewContentTypeValuesState(1))

// 外部接口采集
const externalApiVisible = computed(() => getNewContentTypeValuesState(2))
const getNewContentTypeValuesState = (type: number) => {
  if (formData.value.resource_type !== type || !formData.value.content_type) return false
  const newcontent_typeValues = NEW_CONTENT_TYPE.value.map((m) => m.value)
  return newcontent_typeValues.includes(formData.value.content_type as number)
}

// 资源类型 切换 清空相关字段值
const selectResetValueHandle = (val: any) => {
  console.log('val: ', val)
  formData.value.content_type = undefined // 内容类型
  formData.value.collect_addr = '' // 接口地址
  formData.value.seed_key = '' // 种源密钥
  formData.value.video_resource_type = [] // 文件类型
  formData.value.other_param = '' // 其他参数
  formData.value.interface_type = 1 // 接口类型
  formData.value.data_handing = 1 // 数据处理
  formData.value.site_id = undefined // 采集到站点
  formData.value.status = 1 // 采集到站点

  // bind
  formData.value.bind = []
  if (val === 1) {
  }
  // 获取站点分类
  getStation({
    site_id: undefined,
    site_keyword: undefined,
    site_type: formData.value.resource_type,
    site_status: 1
  })
}

// 内容类型 必须 先选择资源类型，判断是否已选择资源类型
const dropdownVisibleChangeHandle = (open: boolean) => {
  if (!open) return

  if (!formData.value.resource_type) message.warning('请先选择资源类型')
}

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~   获取资源分类 - start   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
let siteClassificationTableData = ref<CollectFormBindType[]>([]) // 站点分类 tableData

// 根据源分类数据 组装站点分类所需 tableData
const setSiteClassificationTableData = (data: SourceClassificationDataType) => {
  return data.map((m: SourceClassificationDataItemType) => ({
    origin_category: m.origin_category,
    origin_sub_category: m.origin_sub_category,
    site_category: undefined,
    site_category_id: undefined,
    site_sub_category: undefined,
    site_sub_category_id: undefined,
    num: m.num,
    selectIds: []
  }))
}

// 获取源分类按钮
let resourceClassifyBtnLoading = ref<boolean>(false)

// 获取源分类数据
const { getSourceClassification } = apis.collectManage
const setSourceClassificationHandle = () => {
  formRef.value.validateFields(['collect_addr']).then(() => {
    if (formData.value.resource_type === 1 && !formData.value.video_resource_type.length) {
      message.warning('请先选择文件类型')
      return
    }

    const params = {
      addr: formData.value.collect_addr,
      key: formData.value.seed_key,
      file_type_list: formData.value.video_resource_type
      // file_type_list: formData.value.video_resource_type + ''
    }
    console.log('params: ', params)

    resourceClassifyBtnLoading.value = true

    getSourceClassification(params)
      .then((res: any) => {
        siteClassificationTableData.value = setSiteClassificationTableData(res.list)
        resourceClassifyBtnLoading.value = false
      })
      .catch(() => {
        resourceClassifyBtnLoading.value = false
      })
  })
}

// 重置 siteClassificationTableData 已绑定的数据
const resetBindSiteClassificationTableData = () => {
  const resetValue = (f: CollectFormBindType) => {
    f.site_category = undefined
    f.site_category_id = undefined
    f.site_sub_category = undefined
    f.site_sub_category_id = undefined
    f.num = 0
    f.selectIds = []
  }

  siteClassificationTableData.value.forEach((f: CollectFormBindType) => {
    resetValue(f)
  })
  // formData.value.bind.forEach((f: CollectFormBindType) => {
  //   resetValue(f)
  // })
}

// 监听 资源类型/内容类型切换时 清空 siteClassificationTableData
watch([() => formData.value.resource_type, () => formData.value.content_type], (n) => {
  if (!n[0] || !n[1]) {
    siteClassificationTableData.value = []

    // API 重新获取站点分类
    // setSourceClassificationHandle()
  }
})

// 重置 siteClassificationTableData
const resetSiteClassificationTableData = () => {
  siteClassificationTableData.value = []
}

// 编辑时 设置 siteClassificationTableData
const editSetSiteClassificationTableData = (data: CollectFormBindType[]) => {
  siteClassificationTableData.value = data
}

// 获取过滤后的 SiteClassificationTableData 去除了 selectIds 字段
const getFilterSiteClassificationTableData = () => {
  return siteClassificationTableData.value.map((m: CollectFormBindType) => {
    const { selectIds, ...other } = m
    return other
  })
}

// 判断站点分类是否全部绑定
const validateSiteClassificationTableData = () => {
  return siteClassificationTableData.value.every((e: CollectFormBindType) => e.selectIds?.length)
}

// 未完全绑定站点分类提示信息
const siteClassificationMessageModel = () => {
  if (formData.value.resource_type === 1) {
    messageModel('源分类与本地分类未完全绑定，可能导致采集的内容无分类信息，采集后需二次编辑维护，确定要继续保存吗？')
  }

  if (formData.value.resource_type === 2) {
    messageModel('源分类与本地分类未完全绑定，未绑定分类的内容将不会被采集，确定要继续保存吗？')
  }
}

// 未完全绑定站点分类消息提示 model
const messageModel = (message: string) => {
  Modal.confirm({
    title: '消息提示',
    content: message,
    onOk() {
      mitt.emit('modal-confirm')
    }
  })
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~   获取资源分类 - end   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// 采集到站点 selectChange
const siteSelectChange = (val: string) => {
  if (!formData.value.resource_type) {
    message.warning('请先选择资源类型')
    return
  }
  if (!formData.value.content_type) {
    message.warning('请先选择内容类型')
    return
  }

  if (!siteClassificationTableData.value.length) {
    message.warning('请点击 "获取资源分类按钮" 以获取源分类信息')
    return
  }

  resetBindSiteClassificationTableData()

  getSiteClassification(formData.value.content_type, { site_id: val })
}

defineExpose({
  editSetSiteClassificationTableData,
  resetSiteClassificationTableData,
  getFilterSiteClassificationTableData,
  validateSiteClassificationTableData,
  siteClassificationMessageModel
})
</script>

<style lang="less" scoped>
.basic-config {
  .resource-type {
    .describe {
      margin-top: 8px;
      font-size: 12px;
      color: #bfbfbf;
    }
  }

  .collect-type {
    .input-content {
      display: flex;
    }

    .describe {
      margin-top: 8px;
      font-size: 12px;
      color: #bfbfbf;
      line-height: 20px;
    }
  }
}
</style>
